package com.cos.hospital.ui.patient;

import android.Manifest;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cos.hospital.R;
import com.cos.hospital.code.Code;
import com.cos.hospital.code.helper.KTextWatcher;
import com.cos.hospital.code.helper.MyOnFreshListener;
import com.cos.hospital.init.BaseActivity;
import com.cos.hospital.model.UHttp;
import com.cos.hospital.model.bean.ErrorBean;
import com.cos.hospital.model.bean.MessageListBean;
import com.cos.hospital.model.bean.ResultBean;
import com.cos.hospital.model.bean.TemplateListBean;
import com.cos.hospital.model.connector.HttpMsgListener;
import com.cos.hospital.tool.MyUtil;
import com.cos.hospital.tool.SPUtil;
import com.cos.hospital.tool.UKeyboard;
import com.cos.hospital.tool.USnackbar;
import com.cos.hospital.tool.USpeech;
import com.cos.hospital.tool.UTxt;
import com.cos.hospital.tool.glide.UGlide;
import com.cos.hospital.ui.patient.adapter.SendMessageAdapter;
import com.cos.hospital.ui.record.adapter.AdapterTemplate;
import com.cos.hospital.widget.MyDividerDecoration;
import com.cos.hospital.widget.MyRecyclerView;
import com.google.gson.JsonObject;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechError;
import com.jude.utils.JTimeTransform;
import com.jude.utils.JUtils;
import com.liaoinstan.springview.container.DefaultFooter;
import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 消息发送
 */
public class SendMessageActivity extends BaseActivity implements RecognizerListener {
    @BindView(R.id.rec_edit_fun_vocal_t)
    TextView iVocalT;
    @BindView(R.id.rec_edit_fun_waves_i)
    ImageView iVocalWaves;
    @BindView(R.id.rec_edit_fun_waves_lay)
    View iVocalWavesLay;
    @BindView(R.id.springView_main)
    SpringView springView;
    @BindView(R.id.rc)
    MyRecyclerView rc;
    @BindView(R.id.edt)
    EditText edt;
    @BindView(R.id.tv_send)
    TextView tv_send;
    @BindView(R.id.iv_more)
    ImageView iv_more;
    @BindView(R.id.rec_edit_fun_lay)
    View layFun;//功能区视图总开关
    @BindView(R.id.rec_edit_fun_speed_lay)
    View laySpeed;//语音视图
    @BindView(R.id.rec_edit_fun_template_lay)
    View layTemplate;//模板视图
    @BindView(R.id.rec_edit_fun_vocal_i)
    ImageView iVocalBtn;
    @BindView(R.id.springView)
    SpringView spv;
    @BindView(R.id.rc_template)
    RecyclerView rvTemplate;
    private List<TemplateListBean.ItemsBean> listTemplate;
    private AdapterTemplate adapterTemplate;
    private List<MessageListBean.ItemsBean> list;
    private BaseQuickAdapter adapter;
    private UKeyboard keyboard;
    private int pageIndex = 1;
    private int patientId;
    private int indexTemplate = 1;

    @Override
    protected int layout() {
        return R.layout.activity_send_message;
    }

    @Override
    protected void init() {
        patientId = getIntent().getIntExtra(Code.SP.ID, 0);
        UKeyboard.SoftHideKeyBoardUtil.assistActivity(this);
        setTitleLeftIcon();
        setTitleCenterTxt("消息发送");
        springView.setHeader(new DefaultFooter(context));
        list = new ArrayList<>();
        adapter = new SendMessageAdapter(list);
        adapter.openLoadAnimation();
        rc.setLayoutManager(new LinearLayoutManager(context));
        adapter.setEmptyView(R.layout.lay_empty, rc);
        rc.addItemDecoration(new MyDividerDecoration(Color.TRANSPARENT, 1));
        rc.setAdapter(adapter);
        edt.setFocusable(true);//可聚焦
        edt.requestFocus();//聚焦
        keyboard = UKeyboard.with(this);
        USpeech.getInstance().init(this);
        UGlide.loadImage(context, R.mipmap.ic_waves, iVocalWaves);
        checkVocalStateUI(false);
        initTemplateAdapter();
    }

    @Override
    protected void logic() {
        springView.setListener(new MyOnFreshListener() {
            @Override
            public void onRefresh() {
                pageIndex++;
                getList();
            }
        });
        rc.setScrollListener(isMoving -> {
            if (keyboard.isKeyboardShow()) {
                keyboard.hideForce(edt);
            }
            if (layFun.isShown()) {
                hideFun();
            }
        });
        edt.addTextChangedListener(new KTextWatcher() {
            @Override
            public void afterTextChanged(Editable editable) {
                String str = editable.toString();
                if (MyUtil.getInstance().getEnterCount(str) > 4) {
                    edt.setText(str.substring(0, str.length() - 1));
                    edt.setSelection(edt.getText().length());//光标末尾
                }
                if (editable.length() > 0) {
                    tv_send.setVisibility(View.VISIBLE);
                    iv_more.setVisibility(View.GONE);
                } else {
                    tv_send.setVisibility(View.GONE);
                    iv_more.setVisibility(View.VISIBLE);
                }
            }
        });
        edt.setOnFocusChangeListener((view, b) -> {
            if (b) {
                edt.setSelection(edt.getText().length());//光标末尾
            }
        });
        getList();
    }

    /**
     * 模板列表
     */
    protected void initTemplateAdapter() {
        listTemplate = new ArrayList<>();
        adapterTemplate = new AdapterTemplate(listTemplate);
        adapterTemplate.openLoadAnimation();//开启默认动画AlphaInAnimation
        rvTemplate.setLayoutManager(new LinearLayoutManager(context));
        adapterTemplate.setEmptyView(R.layout.lay_empty, rvTemplate);//设置当list中元素个数为0时显示的布局
        rvTemplate.addItemDecoration(new MyDividerDecoration(ContextCompat.getColor(context, R.color.white_bg), JUtils.dip2px(1)));
        rvTemplate.setAdapter(adapterTemplate);
        spv.setHeader(new DefaultHeader(context));
        spv.setListener(new MyOnFreshListener() {
            @Override
            public void onRefresh() {
                indexTemplate = 1;
                getTemplateData();
            }
        });
        adapterTemplate.setOnItemClickListener((adapter, view, position) -> {
            if (position >= 0 && position < listTemplate.size()) {
                TemplateListBean.ItemsBean itemsBean = listTemplate.get(position);
                edt.append(itemsBean.getFldContent());
            }
        });
        adapterTemplate.setOnLoadMoreListener(() -> {
            indexTemplate++;
            getTemplateData();
        }, rvTemplate);
    }

    private void send(String content) {
        tv_send.setClickable(false);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("fldSendId", SPUtil.getUserId());
        jsonObject.addProperty("fldReceiveId", patientId);
        jsonObject.addProperty("fldMessageContent", content);
        jsonObject.addProperty("fldMessageStyle", 0);
        UHttp.start(getServes().msgSend(jsonObject), "发送消息", new HttpMsgListener<ResultBean>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                USnackbar.showWarning(context, describe);
            }

            @Override
            public void onFinish() {
                tv_send.setClickable(true);
            }

            @Override
            public void onSuccess(ResultBean dto) {
                if (dto.isSuccess()) {
                    edt.setText("");
                    list.add(new MessageListBean.ItemsBean(content, new JTimeTransform(System.currentTimeMillis() / 1000)
                        .toString("yyyy-MM-dd HH:mm:ss")));
                    adapter.notifyItemInserted(list.size());
                    moveToLast();
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    private void moveToLast() {
        ((LinearLayoutManager) rc.getLayoutManager()).scrollToPositionWithOffset(list.size() - 1, 0);
    }

    private void moveToFirst() {
        ((LinearLayoutManager) rc.getLayoutManager()).scrollToPositionWithOffset(0, 0);
    }

    private void getList() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("fldSendId", SPUtil.getUserId());
        jsonObject.addProperty("fldReceiveId", patientId);
        jsonObject.addProperty("pageIndex", pageIndex);
        jsonObject.addProperty("pageSize", 10);
        UHttp.start(getServes().msgSearch(jsonObject), "发送消息查询", new HttpMsgListener<ResultBean<MessageListBean>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                USnackbar.showWarning(context, describe);
            }

            @Override
            public void onFinish() {
                springView.onFinishFreshAndLoadDelay();
            }

            @Override
            public void onSuccess(ResultBean<MessageListBean> dto) {
                if (dto.isSuccess()) {
                    MessageListBean resultBean = dto.getResult();
                    if (resultBean != null) {
                        int pageIndex = resultBean.getPageIndex();
                        List<MessageListBean.ItemsBean> itemsBeanList = resultBean.getItems();
                        if (itemsBeanList != null && itemsBeanList.size() != 0) {
                            for (MessageListBean.ItemsBean itemsBean : itemsBeanList) {
                                list.add(0, itemsBean);
                            }
                        }
                        adapter.notifyDataSetChanged();
                        if (pageIndex == 1) {
                            moveToLast();
                        } else {
                            moveToFirst();
                        }
                    }
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    @OnClick({R.id.title_back, R.id.edt, R.id.iv_audio, R.id.tv_send, R.id.iv_more, R.id.rec_edit_fun_vocal_i})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                onBackPressed();
                break;
            case R.id.edt:
                hideAll();
                Observable.timer(200, TimeUnit.MILLISECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(aLong -> moveToLast());
                break;
            case R.id.iv_audio:
                showOne(laySpeed, layTemplate);
                break;
            case R.id.tv_send:
                String content = edt.getText() + "";
                send(content);
                break;
            case R.id.iv_more:
                showOne(layTemplate, laySpeed);
                break;
            case R.id.rec_edit_fun_vocal_i://语音:
                if (!iVocalBtn.isSelected()) {
                    speech();
                }
                break;
        }
    }

    private void getTemplateData() {

    }

    private void hideAll() {
        hideFun();//关闭功能区
        UKeyboard.with(this).showForce(edt); //打开键盘
    }

    /**
     * 显示某一个功能区域的布局
     */
    protected void showOne(View... shows) {
        if (keyboard.isKeyboardShow()) {
            keyboard.hideForce(edt);
        }
        edt.postDelayed(() -> {
            layFun.setVisibility(View.VISIBLE);
            for (int i = 0; i < shows.length; i++) {
                if (i == 0) {
                    shows[i].setVisibility(View.VISIBLE);
                } else {
                    shows[i].setVisibility(View.GONE);
                }
            }
        }, 200);
    }

    /**
     * 隐藏全部功能区
     */
    protected void hideFun() {
        layFun.setVisibility(View.GONE);
        laySpeed.setVisibility(View.GONE);
        layTemplate.setVisibility(View.GONE);
    }

    @Override
    public void onBackPressed() {
        if (keyboard.isKeyboardShow()) {
            keyboard.hideForce(edt);
        } else if (layFun.isShown()) {
            hideFun();
        } else {
            super.onBackPressed();
        }
    }

    /**
     * @param open true为目标状态
     * @apiNote 修改语音按钮样式
     */
    private void checkVocalStateUI(boolean open) {
        if (open) {
            iVocalBtn.setSelected(true);
            iVocalWavesLay.setVisibility(View.VISIBLE);
            iVocalT.setText(R.string.vocal_on_say_please);
        } else {
            iVocalBtn.setSelected(false);
            iVocalT.setText(R.string.vocal_off_touch_please);
            iVocalWavesLay.setVisibility(View.INVISIBLE);
        }
    }

    private void speech() {
        RxPermissions rxPermissions = new RxPermissions(this);
        if (!rxPermissions.isGranted(Manifest.permission.RECORD_AUDIO)) {
            rxPermissions.request(Manifest.permission.RECORD_AUDIO)
                .subscribe(granted -> {
                    if (granted) {
                        startListening();
                    } else {
                        MyUtil.getInstance().toSetting(context, "你已拒绝获取录制音频权限，为保证你能正常使用语音输入功能，请开启该权限。", 10, false);
                    }
                });
        } else {
            startListening();
        }
    }

    private void startListening() {
        USpeech.getInstance().startListening(this);
    }

    @Override
    public void onVolumeChanged(int volume, byte[] bytes) {
    }

    @Override
    public void onBeginOfSpeech() {
        checkVocalStateUI(true);
    }

    @Override
    public void onEndOfSpeech() {
        checkVocalStateUI(false);
    }

    @Override
    public void onResult(RecognizerResult recognizerResult, boolean b) {
        String parseIatResult = USpeech.getInstance().parseIatResult(recognizerResult);
        if (parseIatResult == null) {
            USnackbar.showWarning(context, "声音太小,没听清楚");
        } else {
            edt.append(parseIatResult);
        }
    }

    @Override
    public void onError(SpeechError speechError) {
    }

    @Override
    public void onEvent(int i, int i1, int i2, Bundle bundle) {
    }
}
